package easy;

/**
 * Created by daodao on 2017/11/30.
 * Problem 21
 * Description: Merge two sorted linked lists and return it as a new list.
 * The new list should be made by splicing together the nodes of the first two lists.
 */
public class MergeTwoSortedLists {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode p = l1;
        ListNode q = l2;
        ListNode newList;
        if (l1 == null && l2 == null) return null;
        else if (l1 == null && l2 != null) {
            newList = new ListNode(q.val);
            q = q.next;
        }
        else if (l1 != null && l2 == null) {
            newList = new ListNode(p.val);
            p = p.next;
        }
        else {
            if (p.val <= q.val) {
                newList = new ListNode(p.val);
                p = p.next;
            } else {
                newList = new ListNode(q.val);
                q = q.next;
            }
        }
        ListNode cur = newList;

        while (p != null && q != null) {
            if (p.val <= q.val) {
                cur.next = new ListNode(p.val);
                p = p.next;
            } else {
                cur.next = new ListNode(q.val);
                q = q.next;
            }
            cur = cur.next;
        }
        if (p != null) {    // l1有的多
            while (p != null) {
                cur.next = new ListNode(p.val);
                cur = cur.next;
                p = p.next;
            }
        }
        if (q != null) {    // l2有的多
            while (q != null) {
                cur.next = new ListNode(q.val);
                cur = cur.next;
                q = q.next;
            }
        }
        return newList;
    }
}
